package top.yangyitao.dao.impl;

import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import top.yangyitao.dao.RegisterCodeDao;
import top.yangyitao.model.RegisterCode;


@Repository("registerCodeDao")
public class RegisterCodeDaoImpl implements RegisterCodeDao {

	@Resource
	private SessionFactory sessionFactory;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public RegisterCode findRegisterCodeByUserName(String userName) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "from RegisterCode rc where rc.userName = '"+userName+"'";
		Query query = session.createQuery(hql);
		List<RegisterCode> list = query.list();
		if(list.size()>0)
			return list.get(0);
		else
			return null;
	}

	@Override
	public RegisterCode createRegisterCodeByUserName(String userName) {
		Session session = sessionFactory.getCurrentSession();
		String registerTime = String.valueOf(new Date().getTime());
		String code = String.valueOf(new Random().nextInt());
		RegisterCode registerCode = new RegisterCode(registerTime,userName,code);
		session.save(registerCode);
		return registerCode;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void deleteRegisterCodeByUserName(String userName) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "delete from RegisterCode rc where rc.userName = '"+userName+"'";
		Query query = session.createQuery(hql);
		query.executeUpdate();
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public void updateRegisterCodeByUserName(String userName) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "update RegisterCode rc set rc.registerTime = '"+String.valueOf(new Date().getTime())+"' , rc.registerCode = '"+String.valueOf(new Random().nextInt())+"'";
		Query query = session.createQuery(hql);
		query.executeUpdate();
	}
}
